package com.example.mybatisplus.util;

import com.mysql.cj.core.util.Base64Decoder;
import org.apache.tomcat.util.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;


/**
 * @author saintess
 * @create 2016/11/22.
 */
public class DesUtils {
    private static String key = "58563214";
    private static String key1 = "32128158";

    public static String decrypt(String message) throws Exception {

        System.out.println("decrypt:" + message);
        byte[] bytesrc = new Base64().decode(message);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key1.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] retByte = cipher.doFinal(bytesrc);
        return new String(retByte);

    }

    public static String idCardDec(String message) throws Exception {
        String dec = decrypt(message);
        if (dec != null) {
            return dec;
        } else {
            return message;
        }
    }

    public static String encrypt(String message) throws Exception {

        System.out.println("encrypt:" + message);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key1.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        return new String(new Base64().encode(cipher.doFinal(message.getBytes("UTF-8"))));

    }
}
